<template>
	<div class="matrix-checkbox-question">
		<div class="ques-opt-title">
			<i class="star" v-if="dataVal?.attribute?.required"></i>
			<i>{{ index + 1 }}、</i>
			<div contenteditable="true" @keydown="preventEnter" @blur="dataChange($event, dataVal, 'title')">{{ dataVal.title }}</div>
			<div class="ques-opt-title-ope">
				<span @click="$emit('remove', dataVal)" class="delete">✖</span>
				<span class="move">☝</span>
				<input type="checkbox" v-model="isRequired" />
			</div>
		</div>
		<div class="ques-opt-body">
			<table class="ques-opt-item-table">
				<thead>
					<tr>
						<th></th>
						<th v-for="col in dataVal.children" :key="col.id">
							<div class="ques-opt-col">
								<div contenteditable="true" @keydown="preventEnter" @blur="dataChange($event, col, 'title')">{{ col.title }}</div>
								<div v-if="scoreIs">
									（ <span contenteditable="true" @input="doneScore($event, col)">{{ col?.attribute?.score }}</span> 分 ）
								</div>
								<div class="ques-opt-col-ope">
									<span @click="removeRow(dataVal.children, col)" class="delete">✖</span>
								</div>
							</div>
						</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="row in dataVal.row" :key="row.id">
						<td>
							<div class="ques-opt-row">
								<div contenteditable="true" @blur="dataChange($event, row, 'title')">{{ row.title }}</div>
								<div class="ques-opt-row-ope">
									<span @click="removeRow(dataVal.row, row)" class="delete">✖</span>
								</div>
							</div>
						</td>
						<td v-for="col in dataVal.children" :key="col.id">
							<i class="k-checkbox"></i>
						</td>
					</tr>
				</tbody>
			</table>
			<div class="ques-opt-add">
				<span @click="addRow"> ✚ 添加行 </span>
				<span @click="addCol"> ✚ 添加列 </span>
			</div>
		</div>
	</div>
</template>

<script>
import common from "./common.js";
export default {
	mixins: [common],
	methods: {
		doneScore(e, i) {
			i.attribute = i.attribute ?? {};
			i.attribute.score = e.target.innerText.replace(/\D/g, "");
			// 只保留数字，虽然内容来自e，并绑定了i.attribute.score，但还是要重新赋值
			// 这样才能在输入时，实时更新到i.attribute.score,且输入的内容长度不超过2个字符
			if (i.attribute.score.length > 2) {
				i.attribute.score = i.attribute.score.slice(0, 2);
			}
			e.target.innerText = i.attribute.score;
		},
		//添加行
		addRow() {
			let id = this.tool.ids.get();
			let title = "行" + (this.dataVal.row.length + 1);
			this.dataVal.row.push({ id, title });
		},
		addCol() {
			let id = this.tool.ids.get();
			let title = "列" + (this.dataVal.children.length + 1);
			this.dataVal.children.push({ id, title });
		},
		removeRow(rows, row) {
			if (rows.length === 1) {
				this.tip({ msg: "至少保留一行！" });
				return;
			}
			rows.splice(rows.indexOf(row), 1);
		},
		removeCol(cols, col) {
			if (cols.length === 2) {
				this.tip({ msg: "至少保留两列！" });
				return;
			}
			cols.splice(cols.indexOf(col), 1);
		}
	}
};
</script>
